<?php

namespace hiduoke\services\douyinMinApp\API;


class DouyinApi extends BaseApi
{
    // V1接口地址
    public $url_v1 = "https://developer.toutiao.com";
    // V2接口地址
    public $url_v2 = "https://open.douyin.com";
    // 沙盒地址
    public $sandbox_url = "https://open-sandbox.douyin.com";
    // 沙盒
    public $sandbox = false;

    public function __construct($config)
    {
        if (empty($config['appid'])) {
            throw new \Exception('not empty appid');
        }
        if (empty($config['secret'])) {
            throw new \Exception('not empty secret');
        }
        $this->appid = $config['appid'];
        $this->secret = $config['secret'];
        $this->valid_time = isset($config['valid_time']) ? $config['valid_time'] : time() + 900;
    }

    public function getAccessToken()
    {
        $data = [
            'grant_type' => 'client_credential',
            'appid'      => $this->appid,
            'secret'     => $this->secret,
        ];
        $url = $this->getUrl() . "/api/apps/v2/token";
        $res = $this->httpPost($url, $data);
        return $res;
    }

    public function getClientToken()
    {
        $data = [
            'grant_type'    => 'client_credential',
            'client_key'    => $this->appid,
            'client_secret' => $this->secret,
        ];
        $url = $this->getUrl(2) . "/oauth/client_token/";
        $res = $this->httpPost($url, $data);
        return $res;
    }


    public function login($code, $anonymous_code = '')
    {
        $query = [
            'appid'  => $this->appid,
            'secret' => $this->secret,
            'code'   => $code,
        ];
        if ($anonymous_code) {
            $query['anonymous_code'] = $anonymous_code;
        }
        $url = $this->getUrl() . '/api/apps/v2/jscode2session';
        $res = $this->httpPost($url, $query);
        return [
            'errno'   => $res['err_no'],
            'message' => $res['err_tips'],
            'data'    => $res['data']
        ];
    }


    public function getUrl($version = 1)
    {
        if ($this->sandbox) {
            return $this->sandbox_url;
        }
        return $version == 1 ? $this->url_v1 : $this->url_v2;
    }

}
